#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if (root == nullptr) return ret;
        queue<TreeNode*> st;
        st.push(root);
        int i = 0;
        while (st.size())
        {
            vector<int> tmp;
            int n = st.size();
            for (int i = 0; i < n; i++)
            {
                TreeNode* tn = st.front();
                if (tn->left) st.push(tn->left);
                if (tn->right) st.push(tn->right);
                tmp.push_back(tn->val);
                st.pop();
            }
            if (i % 2) reverse(tmp.begin(), tmp.end());
            ret.push_back(tmp);
            i++;
        }
        return ret;
    }
};